package org.bigjava.novelplatform.common.utils;

import org.springframework.util.DigestUtils;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密
 * @author ykh
 * @create 2022-03-22 10:41
 */
public class EncryptUtils {
    /**
     * 使用md5的算法进行加密
     */
    public static String md5(String source){
        if(source == null || source.length()==0 ){
            throw new RuntimeException("空字符");
        }
        //md5加密
        String algorithm = "md5";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            byte[] input = source.getBytes(StandardCharsets.UTF_8);
            //执行加密
            byte[] output = messageDigest.digest(input);
            //加密为正数
            int signum = 1;
            BigInteger bigInteger = new BigInteger(signum, output);
            //数值，16进制表示
            int radix = 16;
            String encoded = bigInteger.toString(radix);
            return encoded;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        DigestUtils.md5DigestAsHex(source.getBytes(StandardCharsets.UTF_8));
        return null;
    }

    /**
     * 加盐
     * @param source
     * @param salt
     * @return
     */
    public static String salt(String source, String salt){
        String sourceMd5 = md5(source);
        String saltMd5 = md5(salt);
        byte[] sourceBytes = sourceMd5.getBytes();
        byte[] saltBytes = saltMd5.getBytes();
        byte[] bs = new byte[32];
        for (int i = 0; i < saltBytes.length; i++) {
            byte s = (byte) (sourceBytes[i] | saltBytes[i]);
            bs[i] = s;
        }
        String s = new String(bs);
        return s;
    }



}
